package com.qlm.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;









import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.qlm.entity.HB;
import com.qlm.service.IHBManageService;
import com.qlm.tools.Common;
import com.qlm.view.ResultMessage;

public class HBManageServiceImpl implements IHBManageService{

	private static Logger logger = LoggerFactory.getLogger(HBManageServiceImpl.class);
	@Override
	public List<HB> getAllHB() {
		List<HB> list =  new ArrayList<HB>();
		list = HB.dao.find("select id,cost,money from t_jf_hb");
		if(Common.isNullOrEmpty(list) || list.size()==0){
			HB hb = new HB();
			hb.set("money", 0).set("cost", "");
			list.add(hb);
		}
		return list;
	}

	@Override
	@Before(Tx.class)
	public ResultMessage saveHb(String[] money_, Integer[] cost_) {
		if(!Common.isNullOrEmpty(money_) && !Common.isNullOrEmpty(cost_)  
				&& money_.length==cost_.length && money_.length>0 && money_.length<=3){
			int len = money_.length;
			String delSql = "delete from t_jf_hb";
			Db.update(delSql);
			for(int i=0;i<len;i++){
				HB hb = new HB();
				int m = new BigDecimal(money_[i]).multiply(new BigDecimal(100)).intValue();
				hb.set("money", m).set("cost", cost_[i]).save();					
			}
			callCache("cache/updateHb");
			return new ResultMessage(1, "保存红包配置成功", null);
		}
		return new ResultMessage(0, "网络连接失败", null);
	}
	
	/**
	 * 发送请求给cache更新
	 * @param type
	 */
	public static void callCache(String type){
			new Thread(new Runnable() {
				public void run() {
					String cacheUrl = PropKit.get("cacheUrl");
					String[] urlArr = cacheUrl.split(",");
					try{						
						for(int i=0;i<urlArr.length;i++){
							if(Common.isEmptyString(urlArr[i])){
								HttpKit.get(urlArr[i] + type);
								logger.info(urlArr[i]+type+"请求发送成功");
							}							
						}
					}catch(Exception e){
						logger.error(e.getMessage(), e);
					}	
				}
			}).start();
	}

}
